//
//  AudioPlayerViewController.swift
//

import UIKit
import AVFoundation
import Alamofire
import CleanJSON

class AudioPlayerViewController: BaseViewController {
    
    static let share = AudioPlayerViewController()
    var playerItemModel = AudioItemModel() /// 正在播放的item
    var didAudioItemModeChange: () -> Void = {} /// 播放的item改变
    
    var dataSource = [AudioItemModel]()
    var audioModel = AudioModel()
    var atype: String = ""
    var playerIndex: Int = 0
    private var id: String = ""
    private var isSingle: Bool = false /// 单曲循环
    
    private lazy var bgImageView: UIImageView = {
        let view = UIImageView(image: "blh_audio_bg".image)
        view.isUserInteractionEnabled = true
        return view
    }()
    
    private lazy var iconImageView: UIImageView = {
        let view = UIImageView()
        view.corner(radii: 8.fit)
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.textColor = UIColor.black
        view.font = 15.font
        view.textAlignment = .center
        return view
    }()
    
    private lazy var bottomView: AudioPlayerBottomView = {
        let view = AudioPlayerBottomView()
        view.didClickPlayer = { [weak self] in
            guard let `self` = self else { return }
            self.player.changePlay()
        }
        view.sliderValueDidChange = { [weak self] value in
            guard let `self` = self else { return }
            let sliderTime = value * self.player.maximumDuration
            self.player.seek(to: CMTime(seconds: sliderTime, preferredTimescale: CMTimeScale(1 * NSEC_PER_SEC)))
        }
        view.sliderTouch = { [weak self] value in
            guard let `self` = self else { return }
            if value == .down {
                self.player.pause()
            } else {
                self.player.play()
            }
        }
        view.didNext = { [weak self] in
            guard let `self` = self else { return }
            self.playerIndex += (self.isSingle ? 0 : 1)
            self.playerURL()
        }
        view.didUp = { [weak self] in
            guard let `self` = self else { return }
            self.playerIndex -= (self.isSingle ? 0 : 1)
            self.playerURL()
        }
        view.didPlayerType = { [weak self] isSingle in
            guard let `self` = self else { return }
            self.isSingle = isSingle
        }
        return view
    }()
    
    private lazy var player: AudioPlayer = {
        let player = AudioPlayer()
        player.delegate = self
        player.playbackPausesWhenResigningActive = false
        player.playbackPausesWhenBackgrounded = false
        player.playbackResumesWhenBecameActive = false
        player.playbackResumesWhenEnteringForeground = false
        return player
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNav()
        addSubviews()
        playerURL()
    }
    
    private func setupNav() {
        navigation.bar.alpha = 0
    }

    private func addSubviews() {
        
        view.addSubview(bgImageView)
        bgImageView.addSubview(iconImageView)
        bgImageView.addSubview(titleLabel)
        bgImageView.addSubview(bottomView)
        
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        iconImageView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(topLayoutGuideBottom).offset(100.fit)
            make.size.equalTo(CGSize(width: 220.fit, height: 220.fit))
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(iconImageView.snp.bottom).offset(8.fit)
        }
        
        bottomView.snp.makeConstraints { (make) in
            make.bottom.equalTo(safeAreaLayoutGuideBottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(110.fit)
        }
    }
    
    func playerURL() {
        if playerIndex < 0 {
            playerIndex = dataSource.count - 1
        }
        if playerIndex > dataSource.count - 1 {
            playerIndex = 0
        }
        
        let model = dataSource[playerIndex]
        /// 选中的id和正在播放的id一致就不做处理
        if model.id == playerItemModel.id {
            return
        }
        
        iconImageView.kf_set(audioModel.album.thumbs.large_thumb)
        titleLabel.text = model.title
        playerItemModel = model
        didAudioItemModeChange()
        if self.atype == "1" {
            id = model.id
            requestURL()
        } else {
            player.player(model.sd_url)
        }
    }
    
    func pause() {
        if !playerItemModel.id.isEmpty {
            player.pause()
        }
    }
}

extension AudioPlayerViewController {
    
    private func requestURL() {
        Network.Rec
            .audio(pid: audioModel.album.id,
                   id: id)
            .request()
            .responseAudioData(AudioModel.self) { [weak self] (model) in
                guard let `self` = self else { return }
                if let firstModel = model.data.editions.first, let url = firstModel.urls.first {
                    self.player.player(url)
                }
        } failure: { (error) in
            Toast.show(info: error.errorMessage)
        }
    }
}

extension AudioPlayerViewController: AudioPlayerDelegate {
    
    func playerStateDidChange(_ player: AudioPlayer) {
        bottomView.playState = player.playState
    }
    
    func playerCurrentTimeDidChange(_ player: AudioPlayer) {
        if player.playState == .playing {
            bottomView.currentTime = player.currentTimeInterval
            bottomView.maxTime = player.maximumDuration
            bottomView.sliderValue = Float(player.currentTimeInterval / player.maximumDuration)
        }
    }
    
    func playerPlaybackDidEnd(_ player: AudioPlayer) {
        /// 如果不是单曲播放的话，playerIndex就+1
        if !isSingle {
            playerIndex += 1
        }
        playerURL()
    }
    
    func player(_ player: AudioPlayer, didFailWithError error: Error?) {
        
    }
}
